<template>
  <div>
    <a-button @click="addItem" type="primary">新增List</a-button>

    <div class="top" :style="{ display: 'flex', justifyContent: 'center' }">
      <a-tag
        :style="{
          width: '80px',
          height: '30px',
          margin: '0 10px',
          lineHeight: '30px',
          textAlign: 'center',
          cursor: 'pointer',
        }"
        :color="item.active ? '#108ee9' : 'blue'"
        @click="toggleTag(item)"
        v-for="item in categoriesList.list"
        >{{ item.name }}</a-tag
      >
    </div>

    <a-modal :width="800" v-model:visible="visible" title="新增" @ok="handleOk">
      <!-- :wrapper-col="{ span: 16 }" -->
      <a-form
        ref="formRef"
        :model="formState"
        name="basic"
        :label-col="{ span: 4 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <a-form-item label="key" name="key">
          <a-input v-model:value="formState.key" />
        </a-form-item>
        <a-form-item label="title" name="title">
          <a-input v-model:value="formState.title" />
        </a-form-item>
        <a-form-item label="分类" name="categories">
          <a-checkbox-group
            v-model:value="chooseCategories.list"
            style="width: 100%"
          >
            <a-checkbox v-for="item in categoriesList.list" :value="item.id">{{
              item.name
            }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="条件" name="show">
          <!-- <a-checkbox-group style="width: 100%"> -->
          <a-checkbox v-model:checked="formState.inList">显示在列表</a-checkbox>
          <a-checkbox v-model:checked="formState.inBanner"
            >显示在Banner</a-checkbox
          >
          <a-checkbox v-model:checked="formState.isFree">是否激励</a-checkbox>
          <!-- </a-checkbox-group> -->
        </a-form-item>
        <a-form-item label="缩略图" name="coverImg">
          <a-input v-model:value="formState.coverImg" />
        </a-form-item>
        <a-form-item label="内容" name="content">
          <mavon-editor :subfield="false" v-model="formState.content" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-table :columns="columns" :data-source="tableData.result">
      <template #headerCell="{ column, record }">
        <template v-if="column.key === 'categories'"> </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'key'">
          {{record.key||'-'}}
        </template>
        <template v-if="column.key === 'isFree'">
          <!-- <a-tag  v-if="record.isFree" color="red">否</a-tag>
          <a-tag v-else color="blue">是</a-tag> -->
           <a-switch checked-children="是" un-checked-children="否" v-model:checked="record.isFree"  @change="()=>switchChange(record)"  />
        </template>
         <template v-if="column.key === 'inList'">
          <!-- {{record.inList?"是":"否"}} -->
           <a-switch checked-children="是" un-checked-children="否" v-model:checked="record.inList"  @change="()=>switchChange(record)"  />
        </template>
        <template v-if="column.key === 'inBanner'">
          <!-- {{record.inBanner?"是":"否"}} -->
           <a-switch checked-children="是" un-checked-children="否" v-model:checked="record.inBanner"  @change="()=>switchChange(record)"  />
        </template>
        <template v-if="column.key === 'categories'">
          <div style="display: flex">
            <a-tag v-for="tag in record.categories" :key="tag.id">
              {{ tag.name }}
            </a-tag>
          </div>
        </template>
        <template v-if="column.key === 'operation'">
          <div :style="{ display: 'flex' }">
            <!-- <a-button type="primary">查看</a-button> -->
            <a-button
              @click="editItem(record)"
              type="primary"
              :style="{ marginLeft: '10px' }"
              >修改</a-button
            >
            <a-popconfirm
              title="Are you sure delete this item?"
              ok-text="Yes"
              cancel-text="No"
              @confirm="confirmDelete(record)"
            >
              <a-button :style="{ marginLeft: '10px' }" type="primary" danger
                >删除</a-button
              >
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script>
import _ from "lodash";
import { SmileOutlined, DownOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { defineComponent, reactive, ref, toRefs } from "vue";
const columns = [
  {
    title: "id",
    dataIndex: "id",
    key: "id",
    width: 10,
  },
  {
    title: "key",
    dataIndex: "key",
    key: "key",
  },
  {
    title: "标题",
    dataIndex: "title",
    key: "title",
  },
  {
    width: 100,
    title: "分类",
    // dataIndex: "categories",
    key: "categories",
  },
  {
    title: "无广告",
    dataIndex: "",
    key: "isFree",
  },
  {
    title: "inList",
    dataIndex: "inList",
    key: "inList",
  },
  {
    title: "inBanner",
    dataIndex: "inBanner",
    key: "inBanner",
  },
  {
    title: "创建时间",
    dataIndex: "create_at",
    key: "create_at",
  },
  // {
  //   title: "最后修改时间",
  //   name: "last_modify_date",
  //   dataIndex: "last_modify_date",
  //   key: "last_modify_date",
  // },
  {
    title: "Action",
    key: "operation",
    fixed: "right",
    width: 100,
  },
];
import { parseData } from "../../tools/tools.js";
import { getList, addList, deleteList, getCategories } from "@/http/api";
export default defineComponent({
  components: {
    SmileOutlined,
    DownOutlined,
  },
  async mounted() {
    this.getTable();
    this.getCategoriesFun();
  },
  setup() {
    const params = ref({
      page: 1,
      pageSize: 10,
    });
    let chooseCategories = reactive({ list: [] });
    let tableData = reactive({ result: [], total: 0 });
    let visible = ref(false);
    const formRef = ref();
    const categoriesList = reactive({
      list: [],
    });
    let formState = reactive({
      title: "",
      categories: [],
      isFree: false,
      content: "",
      coverImg: "https://mmbiz.qpic.cn/mmbiz_jpg/",
      inBanner: false,
      inList: true,
      key: "",
    });
    const confirmDelete = async (item) => {
      const res = await deleteList({ id: item.id });
      if (res.data.status === "success") {
        message.success("删除成功");
        getTable();
      }
    };
    const addItem = () => {
      visible.value = true;
    };

    const onFinish = (values) => {
      console.log("Success:", values);
    };

    const onFinishFailed = (errorInfo) => {
      console.log("Failed:", errorInfo);
    };

    const handleOk = async () => {
      formState.categories = categoriesList.list
        .filter((item) => chooseCategories.list.includes(item.id))
        .map((item) => {
          return {
            id: item.id,
            name: categoriesList.list.filter((i) => i.id == item.id)[0].name,
          };
        });
      // formState.isFree = !formState.isFree;
      const res = await addList(formState);
      if (res.data.id) {
        message.success("操作成功");
        visible.value = false;
        resetForm();
        getTable();
      }
    };
    const switchChange = (item) => {
      for (const key in item) {
        if (key != "categories") {
          formState[key] = item[key];
        }
      }
      handleOk()
    }
    const editItem = (item) => {
      chooseCategories.list = item.categories.map((item) => item.id);
      // console.log(item, chooseCategories.list, "chooseCategories.list");
      for (const key in item) {
        if (key != "categories") {
          formState[key] = item[key];
        }
      }
      visible.value = true;
    };
    const resetForm = () => {
      chooseCategories.list = [];
      formRef.value.resetFields();
    };
    const addCopy = () => {};
    const deleteCopy = (index) => {};
    const getTable = async () => {
      const res = await getList();
      const ids = categoriesList.list
        .filter((item) => item.active)
        .map((i) => i.id);

      if (ids.length > 0) {
        tableData.result = res.data.result.filter(
          (item) =>
            _.intersection(
              ids,
              item.categories.map((item) => item.id)
            ).length > 0
        );
        // console.log(ids, "ids", res.data.result);
      } else {
        tableData.result = res.data.result;
      }
    };

    const getCategoriesFun = async () => {
      const res = await getCategories();
      categoriesList.list = res.data.result.map((item) => {
        item.active = false;
        return item;
      });
    };
    const toggleTag = (item) => {
      item.active = !item.active;
      getTable();
    };
    return {
      chooseCategories,
      getCategoriesFun,
      categoriesList,
      confirmDelete,
      params,
      columns,
      tableData,
      addItem,
      visible,
      formState,
      onFinish,
      onFinishFailed,
      handleOk,
      addCopy,
      deleteCopy,
      formRef,
      resetForm,
      getTable,
      editItem,
      toggleTag,
      switchChange
    };
  },
});
</script>
